<template>
    <div class="register-wrapper">
        <div class="left-part">
            <el-switch
                    v-model="isLoginActive"
                    inline-prompt
                    active-text="登录"
                    inactive-text="注册"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;font-family:'Alibaba_PuHuiTi_2.0_65_Medium_65_Medium';"
                    size="large"
                    width="60px"
                    @change="switchChange(isLoginActive)"
            />
        </div>

        <div class="right-part-register" v-if="isLoginActive">
            <div class="title"><span>注册</span></div>
            <el-form :model="form" :rules="rules" ref="formTable" label-width="auto" style="max-width: 600px"
                     :inline="false" :label-position="left">
                <el-form-item label="用户名:" prop="username">
                    <el-input v-model="form.username" placeholder="长度必须大于5"/>
                </el-form-item>

                <el-form-item label="密码:" prop="password">
                    <el-input
                            v-model="form.password"
                            placeholder="数字+字母+特殊符号组合"
                            show-password autocomplete="off"
                            type="password"
                    />
                </el-form-item>

                <el-form-item label="性别:" prop="gender">
                    <div class="mb-2 flex items-center text-sm">
                        <el-radio-group v-model="form.gender" class="ml-4">
                            <el-radio value="1" size="middle">男</el-radio>
                            <el-radio value="2" size="middle">女</el-radio>
                        </el-radio-group>
                    </div>
                </el-form-item>

                <el-form-item label="电话:" prop="tel">
                    <el-input v-model="form.tel" placeholder="大陆手机号码"/>
                </el-form-item>

                <el-form-item label="邮箱:" prop="email">
                    <el-input v-model="form.email"/>
                </el-form-item>

                <el-form-item label="默认头像:" v-model="avatar" prop="avatar">

                    <div avatar-list-wrapper style="width: 600px; display: flex; flex-wrap: wrap;">
                        <div
                                v-for="(item,index) in imUrls"
                                :key="index"
                                style="width: 80px; height: 80px;"
                                @click="selected(item,index)"
                                :class="{'active':isActive == index}"
                        >
                            <img :src="item.url" alt=""
                                 style="margin-left: 8px; margin-top: 8px; width: 64px; height: 64px;">
                        </div>
                    </div>

                </el-form-item>

                <el-form-item label="个人签名:" prop="signature">
                    <el-input v-model="form.signature" :maxlength="50"/>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                    <el-button type="danger" style="margin-left: 20px;">取消</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="right-part-login" v-if="!isLoginActive">
            <div class="title"><span>登录</span></div>
            <div class="content">
                <div class="user-label"><span>使用账号或者手机号</span></div>
                <div class="user-input">
                    <el-input type="text" v-model="loginform.username"></el-input>
                </div>
                <div class="password-label"><span>密码</span></div>
                <div class="password-input">

                    <!-- 实现方式一 -->
                    <!-- <el-input
                        :type="loginpwdType"
                        v-model="loginform.password"
                    >
                        <template #suffix>
                            <el-icon color="black" @click="onChangePwdType">
                                <component :is="loginpwdType==='password' ? View : Hide"></component>
                            </el-icon>
                        </template>
                    </el-input> -->

                    <!-- 实现方式二 -->
                    <el-input
                            type="password"
                            v-model="loginform.password"
                            show-password autocomplete="off">
                    </el-input>

                </div>
                <div class="button-label">

                    <el-button type="success" round color="#191919" style="width: 200px;" @click="loginSubmit"><span>登录</span></el-button>
                    <el-button type="danger" round color="#191919" style="width: 200px;"><span>取消</span></el-button>

                </div>

            </div>
            <!-- <div class="bottom">
            </div> -->
        </div>


    </div>
</template>


<script setup>

import { reactive,ref} from 'vue'
import { Plus,UploadFilled,Search,View,Hide } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { postLogin } from '../api/userApi'
import { useStore } from 'vuex'

const router = useRouter()

// =================================== 注册逻辑 ===================================

const imUrls = ref(
    [
        {url: 'https://avatars.githubusercontent.com/u/39689863?v=4&size=64'},
        {url: 'https://avatars.githubusercontent.com/u/17539193?v=4&size=64'},
        {url: 'https://avatars.githubusercontent.com/u/22361503?s=60&v=4'},
        {url: 'https://avatars.githubusercontent.com/u/80?s=60&v=4'},
        {url: 'https://avatars.githubusercontent.com/u/218257?s=60&v=4'},
        {url: 'https://avatars.githubusercontent.com/u/498775?s=60&v=4'},
        {url: 'https://avatars.githubusercontent.com/u/33724737?s=64&v=4'},
        {url: 'https://avatars.githubusercontent.com/u/25120803?v=4&size=64'},
        {url: 'https://avatars.githubusercontent.com/u/25742988?v=4&size=64'},
        {url: 'https://avatars.githubusercontent.com/u/46493087?v=4&size=64'},
        {url: 'https://avatars.githubusercontent.com/u/121680374?v=4&size=64'},
        {url: 'https://avatars.githubusercontent.com/u/54520846?v=4&size=64'},
    ]
)

// 登录页面和注册页面的切换标签
const isLoginActive = ref(false)

const isActive = ref(0)

const selected = (item,index) => {
    isActive.value = index
    console.log(item,index);
    // 此时根据isActivate.value确定选中的avatar

}

// do not use same name with ref
const form = reactive({
    username: '',
    password:'',
    gender: '1',
    tel: '',
    email: '',
    signature: '',
    avatar:imUrls.value[isActive.value].url,
})


// const beforeAvatarUpload = (rawFile) => {
//     console.log("上传的文件格式为:",rawFile.type)
//     if (rawFile.type !== 'image/jpeg' && rawFile.type !=='image/png') {
//         ElMessage.error('头像格式必须是:JPG或PNG格式!')
//         return false
//     } else if (rawFile.size / 1024 / 1024 > 2) {
//         ElMessage.error('头像大小不能超过2MB!')
//         return false
//     }
//     return true
// }


const formTable = ref()

// const onSubmit = ()=> {
//     console.log("点击提交");
//     // 查询校验器的结果
//     console.log(formTable.value.validate(valid=>{
//         if(valid){
//             //
//             form.avatar = imUrls.value[isActive.value].url
//             console.log("选中的图片index",isActive.value);
//             console.log("发送注册请求",form);
//         }else{
//             ElMessage.error('表单数据有误,请重新填写')
//         }
//     }));

//     router.push({path:"/ChatRoom"})
// }

// 用户名校验器
const usernameValidator = (rule, value, callback) => {
    if(value.length > 5){
        callback()
    }else{
        callback(new Error("用户名长度必须大于5"))
    }
}

const passwordValidator = (rule, value, callback) => {
    let reg = /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)(?=.*?[~!#@$%^*&()_+{}\[\]|\\;:'",<.>\/?])[a-zA-Z\d~!#@$%^*&()_+{}\[\]|\\;:'",<.>\/?]*$/;
    if(value.length <= 5){
        callback(new Error("用户名长度必须大于5"))
    }else if(!reg.test(value)){
        callback(new Error("密码必须包含字母大小写数字特殊字符组合"))
    }else{
        callback()
    }
}

const telValidator = (rule, value, callback) => {

    // 大陆电话号码正则校验
    let reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/
    console.log(value.length);
    if(value.length != 11){
        callback(new Error("电话号码长度不符"))
    }else if(!reg.test(value)){
        callback(new Error("电话号码格式不正确"))
    }else{
        callback()
    }
}

const emailValidator = (rule, value, callback) => {

    // 大陆电话号码正则校验
    let reg=/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    console.log(value.length);
    if(!reg.test(value)){
        callback(new Error("邮箱格式不正确"))
    }else{
        callback()
    }
}

// 表单验证
const rules = {
    username:[ {validator: usernameValidator, trigger: 'blur'}],
    password:[ {validator: passwordValidator, trigger: 'blur'}],
    tel:[{validator: telValidator, trigger: 'blur'}],
    email:[{validator: emailValidator, trigger: 'blur'}],
}

// swtich切换
const switchChange = (value)=> {
    console.log("进入切换页面, 当前页面是否是注册页面", value);
    if (!value){
        backgroudImgUrl.value = "src/assets/img/pexels-5.jpg"
    }else{
        backgroudImgUrl.value = "src/assets/img/pexels-4.jpg"
    }
}

// 背景图片动态切换
const backgroudImgUrl = ref("src/assets/img/pexels-4.jpg")

// =================================== 登陆逻辑 ===================================
const loginform = reactive({
    username:"",
    password:""
})

const loginpwdType = ref("password")

const onChangePwdType = ()=>{
    // 点击眼睛开放图标后,密码明文显示,眼睛图标变为关闭状态; 同理反之
    console.log("进入showPassword函数");
    if (loginpwdType.value === "password") {
        loginpwdType.value = "text"
    } else {
        loginpwdType.value = "password"
    }
}

const store = useStore()
// 登录
const loginSubmit = ()=> {
    const params = {"username":loginform.username,"password":loginform.password}
    console.log("登录请求发送的参数是:",params);
    postLogin(params).then(res=>{
        store.commit("updateUserInfo",res)
        router.push({
            path:"/index"
        })
    }).catch(err=>{
        console.log("登录错误",err);
    })
}

</script>

<style scoped lang="scss">

.register-wrapper{
    width: 60vw;
    height: 90vh;
    border-radius: 20px;
    // 背景图片,并设置渐变,增加透明度,实现遮罩效果 
    // background-image: url("src/assets/img/pexels-4.jpg");
    background-image: linear-gradient(to right bottom,rgba(22,34,42,0.3),rgba(58,96,115,0.3)),url("src/assets/img/flower.png");
    // 背景图片大小设置
    background-size: cover;
    // 图片位置,缩放后出现的位置
    background-position: top;
    // 图片裁剪
    clip-path: polygon(0 0, 100% 0, 100% 85vh, 0 100%);
    // 方便子组件居中定位
    position: relative;
    // 样式穿透不生效解决方案
    :deep(.active) {
        background-color: #b3e19d;
    }
    .right-part-register{
        padding: 40px;
        background-color: #ecf5ff;
        height:750px;
        width: 700px;
        position:absolute;
        top:50%;
        left:50%;
        transform: translate(-50%, -50%);
        border-radius: 20px;
        :deep(.el-form-item__label){
            letter-spacing: 2px;
            font-family: "Alibaba_PuHuiTi_2.0_65_Medium_65_Medium";
        };
        // 修改el-button中字段的间距
        :deep(.el-button--primary){
            span{
                letter-spacing: 2px;
                font-family: "Alibaba_PuHuiTi_2.0_65_Medium_65_Medium";
            }
            
        }
        .title {

            position: relative;
            span{
                font-size: 40px;
                font-weight: bold;
                display: inline-block;
                color: #58585B;
                // 设置字体之间间距
                letter-spacing: 20px;
                position:absolute;
                left:50%;
                transform: translateX(-50%);
                font-family: "Alibaba_PuHuiTi_2.0_65_Medium_65_Medium";
            }
            height: 10%;
            margin-bottom: 50px;
            // 设置进入动画
            animation-name: titleInLeft;
            animation-duration: 2s;
            animation-timing-function:calc(0);
        }
    }

    .right-part-login {
        padding: 40px;
        background-color: #ecf5ff;
        height:400px;
        width: 700px;
        border-radius: 20px;
        position: absolute;
        // 相对父组件的宽度和高度
        top: 50%;
        left: 50%;
        // 相对本身的宽度和高度，组合top和left实现居中效果
        transform: translate(-50%, -50%);
         span{
            color: #6C6E72;
            font-family: 'Roboto', Arial, sans-serif;
            // font-weight: bold;
            font-size:15px;
            letter-spacing: 2px;
            font-family: "Alibaba_PuHuiTi_2.0_65_Medium_65_Medium";
        }
        .title{
            position: relative;
            span{
                font-size: 40px;
                font-weight: bold;
                display: inline-block;
                color: #58585B;
                // 设置字体之间间距
                letter-spacing: 20px;
                position:absolute;
                left:50%;
                transform: translateX(-50%);
                text-align: center;
                font-family: "Alibaba_PuHuiTi_2.0_65_Medium_65_Medium";
            }
            height: 10%;
            margin-bottom: 50px;
            // 设置进入动画
            animation-name: titleInLeft;
            animation-duration: 2s;
        }
        .content{

            height: 40%;
            .button-label{
                margin-top: 20px;
                span{
                    font-size: 20px;
                    color: white;
                }
            }
            .password-label{
                margin-top: 10px;
            }
            .button-label {
                display: flex;
                justify-content:flex-start;
                margin-top: 50px;
            }
        }
        .bottom {
            width: 100%;
            // background-color: red;
            margin-top: 10px;
            height: 50%;
        }
    }             
    .left-part {
        margin-left: 10px;
        margin-top: 10px;
    }

     // 设置动画
    @keyframes titleInLeft {
        // 开始位置
        0%{
            opacity: 0;
            transform: translate(-50px);
        }
        // 中间位置
        50%{
            opacity: 0.5;
            transform: translate(50px);
        }
        // 结束位置
        100%{
            opacity: 1;
            transform: translate(0);
        }
    }

}

</style>